package com.nash.demands;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.text.InputType;
import android.widget.EditText;
import android.widget.Toast;

public class AmountDialog {
  private long clickedId;
  public void editAmount(final DocStockActivity caller, long id) {
    clickedId=id;
    AlertDialog.Builder alert = new AlertDialog.Builder(caller);

    alert.setTitle("Укажите количество");

    // Set an EditText view to get user input
    final EditText input = new EditText(caller);
    input.setInputType(InputType.TYPE_CLASS_NUMBER);
    input.setSelectAllOnFocus(true);
    
    int amount = 0;
    Cursor c = DemandsActivity.db.query(DocTabActivity.TBL_TEMP_ITEM, new String[] { DocTabActivity.TBL_TEMP_ITEM_AMOUNT + " as amount" }, DocTabActivity.TBL_TEMP_ITEM_ID_TU + "=?", new String[] { "" + clickedId },
        null, null, null);
    if (c.getCount() > 0) {
      c.moveToFirst();
      amount = c.getInt(c.getColumnIndex("amount"));
    }
    c.close();

    input.setText(amount == 0 ? "" : (new Integer(amount)).toString());
    alert.setView(input);

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
        Integer value;
        try {
          String s = input.getText().toString();
          if (s.trim().equals(""))
            value = new Integer(0);
          else
            value = new Integer(s);
          if (value.intValue() == 0)
            DemandsActivity.db.execSQL("delete from temp_item where id_tu=" + clickedId);
          else{
            float price=0;
            Cursor c = DemandsActivity.db.query(Helper.TBL_TU, new String[] { Helper.TBL_TU_PRICE + " as price" }, BaseColumns._ID + "=?", new String[] { "" + clickedId },
                null, null, null);
            if (c.getCount() > 0) {
              c.moveToFirst();
              price = c.getFloat(c.getColumnIndex("price"));
            }
            c.close();
            DemandsActivity.db.execSQL("replace into temp_item(id_tu,amount,price) values(" + clickedId + "," + value.toString() + ","+String.valueOf(price) +")");
            //((DocStockActivity.TuAdapter)caller.list.getAdapter()).refill();
          }
          caller.setTuAdapter();
        } catch (NumberFormatException e) {
          Toast.makeText(caller, "Invalid number", Toast.LENGTH_SHORT).show();
        }
      }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int whichButton) {
        // Canceled.
      }
    });
    alert.show();
  }

}
